<template>
  <div class="pagestyle">
    <topbottomCom :optionsquery="2" :style="{ width: state.listBtnType == 7 ? '78%' : '100%' }">
      <template v-slot:dragTopSlot>
        <list_controller  ref="zujianname" :options="state.options" @cellClickEvent="cellClickEvent"
          :showCaozuo="state.showCaozuo">
          <template v-slot:opraCurdBtnAll>
            <span :class="
                state.listBtnType == 1 ? 'listInfoBtn active' : 'listInfoBtn'
              " @click="listInfoBtnClick(1)">
              <svg-icon :class="state.listBtnType == 1 ? 'active' : ''" class-name="search-icon" icon-class="qiehuan" />
              历史报警
            </span>
            <span :class="
                state.listBtnType == 2 ? 'listInfoBtn active' : 'listInfoBtn'
              " @click="listInfoBtnClick(2)">
              <svg-icon :class="state.listBtnType == 2 ? 'active' : ''" class-name="search-icon"
                icon-class="shouyetaishifenxi" />
              态势分析
            </span>
            <span :class="state.listBtnType == 7 ? 'listInfoBtn active' : 'listInfoBtn'" @click="listInfoBtnClick(7)">
              <svg-icon :class="state.listBtnType == 7 ? 'active' : ''" 
              class-name="search-icon" icon-class="tongjishuju" />
              统计数据
            </span>
          </template>
          <template v-slot:opraCurdBtnlist="row">
            <span>
              <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row,1)">填写分析
              </el-button>
              <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)"
                v-if="row.row.row.templateDto != null">查看分析</el-button>
            </span>
          </template>
          <template v-slot:listSS="{ row, field }">
            <div v-if="field == 'sensorType'">
              <el-tag type="primary" v-if="row.sensorType == '开关量'">
                {{row.sensorType}}
              </el-tag>
              <el-tag style="color:#7777ee;border-color:#7777ee;" color="rgba(119, 119, 238, 0.1)"
                v-if="row.sensorType == '模拟量'">
                {{row.sensorType}}
              </el-tag>
            </div>
            <div v-if="field == 'status'">
              <span v-if="row.status !=null">
                <el-tag type="danger" v-for="item in row.status.split(',')" style="margin-right: 5px;" :key="item">
                  {{item }}
                </el-tag>
              </span>
            </div>
            <div v-if="field == 'deviceStatus'">
              <el-tag type="danger" v-if="row.deviceStatus?.includes('网络故障')">
                {{row.deviceStatus}}
              </el-tag>
              <el-tag type="warning" v-else-if="row.deviceStatus?.includes('分站故障')">
                {{row.deviceStatus}}
              </el-tag>
              <el-tag type="primary" v-else-if="row.deviceStatus">
                {{row.deviceStatus}}
              </el-tag>
            </div>
          </template>
          <template v-slot:selectNamelist> 实时报警 </template>
        </list_controller>
      </template>
      <template v-slot:dragBottomSlot>
        <list_controller ref="zujiannametwo" :options="state.optionstwo" @query="query">
          <template v-slot:opraCurdBtnlist="row">
            <span>
              <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row,2)">填写分析
              </el-button>
              <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)"
                v-if="row.row.row.templateDto != null">查看分析</el-button>
            </span>
          </template>
          <template v-slot:selectNamelist> 报警结束待处理 </template>
          <template v-slot:listSS="{ row, field }">
            <div v-if="field == 'sensorType'">
              <el-tag type="primary" v-if="row.sensorType == '开关量'">
                {{row.sensorType}}
              </el-tag>
              <el-tag style="color:#7777ee;border-color:#7777ee;" color="rgba(119, 119, 238, 0.1)"
                v-if="row.sensorType == '模拟量'">
                {{row.sensorType}}
              </el-tag>
            </div>
            <div v-if="field == 'alarmTypeStr'">
              <el-tag type="danger" v-if="row.alarmTypeStr.includes('报警')">
                {{row.alarmTypeStr}}
              </el-tag>
              <el-tag type="warning" v-if="row.alarmTypeStr.includes('标校')">
                {{row.alarmTypeStr}}
              </el-tag>
            </div>
            <div v-if="field == 'deviceStatus'">
              <el-tag type="danger" v-if="row.status.includes('网络故障')">
                {{row.deviceStatus}}
              </el-tag>
              <el-tag type="warning" v-else-if="row.status.includes('分站故障')">
                {{row.deviceStatus}}
              </el-tag>
              <el-tag type="primary" v-else-if="row.deviceStatus">
                {{row.deviceStatus}}
              </el-tag>
            </div>
          </template>
        </list_controller>
      </template>
    </topbottomCom>
    <!-- 填写分析 -->
    <fillayaCom :fillayaComShow="state.fillayaComShow" @submitFormfillayaCom="submitFormfillayaCom" :status="'E'">
    </fillayaCom>
    <ayadetailCom :detailsList="state.detailsList" :detailsShow="state.detailsShow"></ayadetailCom>
    <ayasdataCom style="width: 21.5%" v-if="state.listBtnType == 7" @close="close" :dataOption="state.dataOption">
      <template v-slot:ayasContent>
        <ayasCardCom title="实时报警区域统计" :list="state.ayasObjData.oneList.length">
          <template v-slot:rightoperate>
            <span class="rightayasSel">
              <span @click="rightayasSelTypeClick(item)"
                :class="state.ayasObjData.rightayasSelType==item.type?'active':''"
                v-for="item in [{type:'O',label:'近24小时'},{type:'S',label:'近7天'}]">
                {{ item.label }}
              </span>
            </span>
          </template>
          <template v-slot:operatecontent>
            <div class="ayasTjBox">
              <div class="ayasTjBoxdesc" v-for="item in state.ayasObjData.oneList">
                <p>{{item.areaName}}</p>
                <p><em>{{item.count}}</em>次</p>
              </div>
            </div>
          </template>
        </ayasCardCom>
        <ayasCardCom title="近24小时异常统计" :list="3">
          <template v-slot:operatecontent>
            <div class="yichangBox">
              <div class="itemBox" @click="toLSPage('Cx_hisAlarmList')">
                <img src="@/assets/images/abnormal.png" alt="" />
                <p>报警</p>
                <p class="num" style="color: rgba(255, 153, 0, 1);">{{ state.ayasObjData.twoObj.alarmCount }}</p>
              </div>
              <div class="itemBox" @click="toLSPage('Cx_hisCutList')">
                <img src="@/assets/images/abnormal.png" alt="" />
                <p>断电</p>
                <p class="num" style="color: rgba(255, 85, 85, 1);">{{ state.ayasObjData.twoObj.cutCount }}</p>
              </div>
              <div class="itemBox" @click="toLSPage('Cx_hisFeedList')">
                <img src="@/assets/images/abnormal.png" alt="" />
                <p>馈电</p>
                <p class="num" style="color: rgba(238, 102, 187, 1);">{{ state.ayasObjData.twoObj.feedCount }}</p>
              </div>
            </div>
          </template>
        </ayasCardCom>
        <ayasCardCom title="报警次数及时长统计" :list="state.ayasObjData.threeList.length">
          <template v-slot:rightoperate>
            <span class="rightayasSel">
              <span @click="threeClick(item)" :class="state.ayasObjData.threeSelType==item.type?'active':''"
                v-for="item in [{type:'O',label:'近24小时'},{type:'S',label:'近7天'}]">
                {{ item.label }}
              </span>
            </span>
          </template>
          <template v-slot:operatecontent>
            <div id="chartBox" style="width: 100%;height: 200px;">
            </div>
          </template>
        </ayasCardCom>
        <ayasCardCom title="区域报警分布统计" :list="state.ayasObjData.fourList.length">
          <template v-slot:operatecontent>
            <div id="chartBoxt" style="width: 100%;height: 200px;">
            </div>
          </template>
        </ayasCardCom>
      </template>
    </ayasdataCom>
    <!-- 详情 -->
    <el-drawer v-model="state.drawerShow" direction="rtl" size="50%" 
    close-on-click-modal :modal="true">
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title" style="color:#3E464F;margin:0;">
          <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>态势分析</span></h4>
      </template>
      <div>
        <realChartCom :pointDataList="state.pointDataList" :drawerShow="state.drawerShow"></realChartCom>
      </div>
    </el-drawer>
  </div>
</template>
<script setup>
  import topbottomCom from "./listCom/topbottomCom.vue";
  import list_controller from "@/components/commonCom/list_controller";
  import fillayaCom from "./listCom/fillayaCom.vue";
  import ayadetailCom from "./listCom/ayadetailCom.vue";
  import ayasdataCom from "./listCom/ayasdataCom.vue";
  import ayasCardCom from "./listCom/ayasCardCom.vue";
  import realChartCom from "./listCom/realChartCom.vue";
  import {
    computed,
    onMounted,
    reactive,
    nextTick
  } from "vue";
  import {
    table_headers
  } from "@/components/commonCom/table_headers";
  import axios from "@/utils/request";
  import usePagesStore from "@/store/modules/pages";
  import dayjs from "dayjs";
  import * as echarts from "echarts";
  import {
    searchareaTree
  } from "@/api/config";
  import {
    Bottom
  } from "@element-plus/icons-vue";
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore();
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP;
  const upload = ref(null);
  let state = reactive({
    ayasObjData: {
      rightayasSelType: 'S',
      oneList: [],
      twoObj: {},
      threeSelType: 'S',
      threeList: [],
      fourList: []
    },
    detailsShow: false,
    detailsList: [],
    tempList: [],
    fillayaComShow: false, //控制填写分析抽屉显示
    listBtnType: undefined,
    options: {
      refreshShow: true,
      tableheads: computed(() => table_headers.realPointAlarm),
      listSS: [{
          field: "sensorType"
        },
        {
          field: "status"
        },
        {
          field: "deviceStatus"
        },
      ],
      queryList: {
        querys: [],
      },
      dataUrl: "/realPointAlarm/listRealPointAlarms",
    },
    optionstwo: {
      queryList: {
        querys: [{
            fieldsearch: "conditionType",
            field: "conditionType",
            title: "查询方式",
            type: "radiospecial",
            binddata: 1,
            options: [{
                label: "时间查询",
                value: 1,
              },
              {
                label: "班次查询",
                value: 2,
              },
            ],
          },
          {
            field: ["alarmStartTime", "endTime"],
            fieldsearch: ["alarmStartTime", "endTime"],
            title: "时间范围",
            type: "datetimestartEnd",
            binddata: [dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'), dayjs().format(
              'YYYY-MM-DD HH:mm:ss')],
            typespecial: 2,
            show: false,
          },
          {
            field: "datetime",
            fieldsearch: "datetime",
            title: "日期",
            type: "datetime",
            binddata: dayjs().format('YYYY-MM-DD'),
            typespecial: 1,
            show: true,
          },
          {
            fieldsearch: "banci",
            field: "banci",
            title: "班次选择",
            type: "selectspecial",
            binddata: "",
            options: [],
            typespecial: 1,
            show: true,
          },
          {
            field: "condition",
            title: "测点类型",
            type: "cascaderRadio",
            binddata: "",
            options: [],
            props: {
              children: "children",
              value: "code",
              label: "name",
              checkStrictly: true,
              emitPath: false,
            },
          },
          {
            fieldsearch: ["sensorName", "pointId", "place"],
            field: ["sensorName", "pointId", "place"],
            title: "选择测点",
            type: "cascaderRadioSpecial",
            binddata: "",
            options: [],
            props: {
              children: "children",
              value: "commonField",
              label: "commonField",
              checkStrictly: true,
              emitPath: false,
            },
          },
          {
            field: "area",
            title: "所在区域",
            type: "cascaderRadionarmal",
            binddata: "",
            options: [],
            props: {
              children: "childList",
              value: "areaName",
              label: "areaName",
              checkStrictly: true,
              emitPath: false,
            },
          },
          {
            field: "calibrationStatus",
            title: "数据",
            type: "radio",
            binddata: 3,
            options: [{
                label: "全部",
                value: 3,
              },
              {
                label: "报警",
                value: 2,
              },
              {
                label: "标校",
                value: 1,
              },
            ],
          },
          {
            field: "isOpen",
            title: "高级搜索",
            type: "switchgaoji",
            binddata: false,
          },
          {
            field: "alarmDurationTime",
            titlegaoji: "报警时长",
            type: "selectSenior",
            binddata: "",
            options: [{
                label: '1分钟',
                value: 1,
              },
              {
                label: '3分钟',
                value: 3,
              },
              {
                label: '5分钟',
                value: 5,
              },
              {
                label: "10分钟以上",
                value: 10,
              },
            ],
            show: true,
          },
          {
            field: "alarmExtremum",
            titlegaoji: "报警极值",
            type: "inputSenior",
            binddata: "",
            options: [],
            show: true,
          },
          {
            field: "measureMessage",
            titlegaoji: "报警措施",
            type: "inputSenior",
            binddata: "",
            options: [],
            show: true,
          },
        ],
      },
      listSS: [{
          field: "sensorType"
        },
        {
          field: "alarmTypeStr"
        },
        {
          field: "deviceStatus"
        },
      ],
      tableheads: computed(() => table_headers.hisPointAlarm),
      dataUrl: "/hisPointAlarm/listHisPointAlarms",
    },
    editId: undefined,
    banciList: [],
    num: 0,
    areaObj: {},
    descObj: {},
    dataOption: {
      oneTitle: '实时报警区域',
      twoTitle: '近24小时异常统计',
      threeTitle: '设备报警次数及时长统计',
      fourTitle: '区域报警分布统计',
      oneUrl: '/realPointAlarm/attainRealAreaInfo',
      twoUrl: '/realPointAlarm/attainAnomalyInfo',
      threeUrl: '/realPointAlarm/listAlarmInfoStatistic',
    },
    drawerShow: false,
    pointDataList: [],
  });
  /**
   * 统计数据
   */
  function getoneList() {
    axios.post('/realPointAlarm/attainRealAreaInfo', {
      type: state.ayasObjData.rightayasSelType
    }).then(res => {
      state.oneList = res.data.alarmAreaStatisticDtoList
    })
  }
  // 24小时异常
  function getattainAnomalyInfo() {
    axios.get('realPointAlarm/attainAnomalyInfo').then(res => {
      state.ayasObjData.twoObj = res.data
    })
  }
  // 统计数据
  function rightayasSelTypeClick(item) {
    state.ayasObjData.rightayasSelType = item.type
    getoneList()
  }



  function threeClick(item) {
    state.ayasObjData.threeSelType = item.type
    getlistAlarmInfoStatistic()

  }
  function toLSPage(url){
      router.push({
        name: url
      })
  }
  let chartBox, chartBoxt

  function setC1(xdata, data, data1) {
    console.log(xdata, data, data1)
    let option = {
      grid: {
        bottom: 30,
        right: 40
      },
      legend: {
        show: true,
        x: "center",
        textStyle: {
          color: "rgba(62, 70, 79, 1)",
        },
      },
      xAxis: [{
        type: "category",
        boundaryGap: false,
        axisLabel: {
          color: 'rgba(62, 70, 79, 1)',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(62, 70, 79, 1)",
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: "#195384",
          },
        },
        data: xdata,
      }],
      yAxis: [{
          type: "value",
          name: "次数",
          axisLabel: {
            textStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#11366e",
            },
          },
        },
        {
          type: "value",
          name: "时长",
          axisLabel: {
            textStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisLine: {
            lineStyle: {
              color: "rgba(62, 70, 79, 1)",
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: "#11366e",
            },
          },
        },
      ],
      series: [{
          name: "报警次数",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          itemStyle: {
            normal: {
              lineStyle: {
                color: "rgba(68, 170, 255, 1)",
                width: 2,
              },
            },
          },
          data: data,
        },
        {
          name: "报警时长",
          type: "line",
          yAxisIndex: 1,
          symbol: "none",
          itemStyle: {
            normal: {
              lineStyle: {
                color: "rgba(95, 212, 171, 1)",
                width: 2,
              },
            },
          },
          data: data1,
        }
      ],
    };
    chartBox.setOption(option, true)
  }

  function getlistAlarmInfoStatistic() {
    axios.post('realPointAlarm/listAlarmInfoStatistic', {
      type: state.ayasObjData.threeSelType
    }).then(res => {
      state.ayasObjData.threeList = res.data.alarmInfoStatisticDtoList
      let xdata = res.data.alarmInfoStatisticDtoList.map(item => {
        return item.sensorName + '\n' + item.pointId
      })
      let data = res.data.alarmInfoStatisticDtoList.map(item => {
        return item.alarmCount
      })
      let data1 = res.data.alarmInfoStatisticDtoList.map(item => {
        return item.alarmTime
      })
      nextTick(() => {
        chartBox = echarts.init(document.getElementById("chartBox"));
        setC1(xdata, data, data1)
      })
    })
  }

  function setC2(xdata, data) {
    let option = {
      grid: {
        left: 50,
        bottom: 30,
        right: 30
      },
      xAxis: {
        show: false,
      },
      yAxis: [{
          show: true,
          data: xdata,
          inverse: true,
          axisLine: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "rgba(62, 70, 79, 1)",
            rich: {
              lg: {
                backgroundColor: "#339911",
                color: "#fff",
                borderRadius: 15,
                // padding: 5,
                align: "center",
                width: 15,
                height: 15,
              },
            },
          },
        },
        {
          show: true,
          inverse: true,
          data: data,
          axisLabel: {
            show: true,
            inside: false,
            textStyle: {
              color: "rgba(62, 70, 79, 1)",
              fontSize: "12",
            },
            formatter: function (val) {
              return `${val}`;
            },
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
      ],
      series: [{
          type: "bar",
          yAxisIndex: 0,
          data: data,
          barWidth: 30,
          itemStyle: {
            normal: {
              color: " #56A7FF",
            },
          }}],
      };
      chartBoxt.setOption(option, true)
    }

    function getattainRealAreaInfo2() {
      axios.post('realPointAlarm/attainRealAreaInfo', {
        type: 'S'
      }).then(res => {
        state.ayasObjData.fourList = res.data.alarmAreaStatisticDtoList
        let xdata = res.data.alarmAreaStatisticDtoList.map(item => {
          return item.areaName
        })
        let data = res.data.alarmAreaStatisticDtoList.map(item => {
          return item.count
        })
        nextTick(() => {
          chartBoxt = echarts.init(document.getElementById("chartBoxt"));
          setC2(xdata, data)
        })
      })
    }
    // 填写分析抽屉
    function lookBtn(row, n) {
      state.editId = row.id;
      state.num = n;
      state.fillayaComShow = dayjs().unix();
    }
    // 提交填写分析
    function submitFormfillayaCom(data) {
      let dataObj = {};
      dataObj.id = state.editId;
      dataObj.templateDto = data;
      if (data) {
        let url
        if (state.num == 1) {
          url = '/realPointAlarm/modifyRealAnalysis'
        } else {
          url = '/hisPointAlarm/modifyHisAnalysis'
        }
        axios.post(url, dataObj).then((res) => {
          proxy.$modal.msgSuccess(res.msg);
          state.fillayaComShow = false;
          if (state.num == 1) {
            proxy.$refs.zujianname.getData();
          } else {
            proxy.$refs.zujiannametwo.getData();
          }
        });
      } else {
        state.fillayaComShow = false;
      }
    }

    function listInfoBtnClick(type) {
      state.listBtnType = type;
      if (type == 1) {
        goPage()
      }
      if (type == 2) {
        if (proxy.$refs.zujianname.vxe.state.records.length > 0) {
          state.drawerShow = true
          state.pointDataList = proxy.$refs.zujianname.vxe.state.records
        } else {
          proxy.$modal.msgWarning('请先选择数据!')
        }
      }
      if (type == 7) {
        getoneList()
        getattainAnomalyInfo()
        getlistAlarmInfoStatistic()
        getattainRealAreaInfo2()
      }
    }
    // 编辑按钮
    function editBtn(row) {
      if (row.templateDto != null) {
        state.detailsShow = dayjs().unix();
      }
      state.detailsList = row.templateDto;
    }
    // 跳转历史报警异常页面
    const goPage = () => {
      router.push({
        name: 'Cx_hisAlarmList'
      })
    }

    function getbanciList() {
      axios.post("/class/info/searchAll", {}).then((res) => {
        state.banciList = res.data.list;
        state.optionstwo.queryList.querys.forEach((item) => {
          if (item.fieldsearch == "banci") {
            item.options = res.data.list.map((item) => {
              return {
                label: item.className,
                value: item.id,
              };
            });
            item.binddata = item.options[0].value
          }
        });
      });
    }
    getbanciList();

    function banciList(dataObj) {
      axios.post("/hisPointFeed/handleClassInfo", dataObj).then((res) => {
        state.optionstwo.queryList.querys.forEach((item) => {
          if (item.type == "datetimestartEnd") {
            item.binddata = [res.data.feedStartTime, res.data.feedEndTime];
          }
        });
      });
    }

    function getSelList() {
      axios.post("/hisPointFeed/listAllNames", {
        flag: true
      }).then((res) => {
        state.optionstwo.queryList.querys.forEach((item) => {
          if (item.field == "condition") {
            item.options = res.data;
          }
        });
      });
      searchareaTree().then((res) => {
        state.optionstwo.queryList.querys.forEach((item) => {
          if (item.field == "area") {
            item.options = res.data;
          }
        });
      });
    }
    function query(val){
      if(val.type==4){
        state.areaObj.condition=val.val
        getconditionList(state.areaObj)
      }
    }

    function getconditionList(val) {
      axios
        .post("/hisPointFeed/conditionList", val)
        .then((res) => {
          state.optionstwo.queryList.querys.forEach((item) => {
            if (item.type == "cascaderRadioSpecial") {
              item.options = res.data;
            }
          });
        });
    }
    getconditionList(state.areaObj)

    getSelList()
    // 关闭统计数据
    const close = () => {
      state.listBtnType = undefined
    }
    onMounted(() => {

    });
</script>
<style lang="scss" scoped>
  .pagestyle {
    display: flex;
    justify-content: space-between;
  }

  .xiazai {
    position: absolute;
    top: 42px;
    right: 110px;
    width: 120px;
    height: 64px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: space-between;
    background-color: #ffff;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    border-radius: 2px;
    z-index: 99;

    .item {
      width: 100%;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .item:hover {
      background-color: #ececec;
    }
  }

  ::v-deep .el-drawer {
    .querycss {
      .fsc {
        &:nth-child(2) {
          display: none;
        }
      }
    }

    .table_box {
      .fsc {
        display: none;
      }
    }
  }
</style>